import {
  createRouter,
  createWebHashHistory,
  createWebHistory,
} from 'vue-router';

import { resetStaticRoutes } from '@vben/utils';

import { createRouterGuard } from './guard';
import { routes } from './routes';

// 临时添加产品导入页面的静态路由，解决404问题
const productImportRoute = {
  name: 'ProductImport',
  path: '/product/import',
  component: () => import('../views/product/product/Import.vue'),
  meta: {
    title: '产品数据导入',
    permission: ['product:product:import'],
    // 跳过动态路由检查
    ignoreAccess: true,
  },
};

/**
 *  @zh_CN 创建vue-router实例
 */
// 将产品导入路由添加到路由列表中
const existingRoute = routes.find((route) => route.name === 'ProductImport');
if (!existingRoute) {
  routes.push(productImportRoute);
}

const router = createRouter({
  history:
    import.meta.env.VITE_ROUTER_HISTORY === 'hash'
      ? createWebHashHistory(import.meta.env.VITE_BASE)
      : createWebHistory(import.meta.env.VITE_BASE),
  // 应该添加到路由的初始路由列表。
  routes,
  scrollBehavior: (to, _from, savedPosition) => {
    if (savedPosition) {
      return savedPosition;
    }
    return to.hash ? { behavior: 'smooth', el: to.hash } : { left: 0, top: 0 };
  },
  // 是否应该禁止尾部斜杠。
  // strict: true,
});

const resetRoutes = () => resetStaticRoutes(router, routes);

// 创建路由守卫
createRouterGuard(router);

export { resetRoutes, router };
